package me.helllp.book.netty.step08;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter{
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		SubscribeReqProto.SubscribeReq body = (SubscribeReqProto.SubscribeReq)msg;
		
		System.out.println("时间服务器收到的消息：" + body );
		
		SubscribeResProto.SubscribeRes.Builder builder = SubscribeResProto.SubscribeRes.newBuilder();
		
		builder.setSubReqId(body.getSubReqId()).setDesc("这是一个描述").setResCode(232);
		
//		ByteBuf buf = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.writeAndFlush(builder.build());
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
